<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--菜单数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入菜单名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :highlight-current="true"
            :data="treeListArr"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expanded-keys="defaultExpandTree"
            :current-node-key="defaultCurrentKey"
            node-key="id"
            ref="tree"
            accordion
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          label-position="left"
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="90px"
        >
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="菜单状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDatePick"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
        </el-row>

        <el-table
          border
          stripe
          fit
          v-loading="loading"
          max-height="650"
          :data="articleList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection" width="55" align="center" />
          <template v-for="(item, index) in tableHeadList">
            <el-table-column
              align="center"
              :key="index"
              :label="item.label"
              :prop="item.prop"
            >
              <template slot-scope="scope">
                <el-image
                  v-if="item.prop === 'coverImage'"
                  style="height: 50px; width: 50px; line-height: 50px"
                  :src="$initImage(scope.row.coverImage)"
                  :preview-src-list="srcList"
                >
                  <template #error>
                    <div class="image-slot">
                      <span>暂无</span>
                    </div>
                  </template>
                </el-image>
                <span v-else-if="item.prop === 'detail'">
                  <template v-if="scope.row.type == 'image'">
                    <el-image
                      style="height: 50px; width: 50px; line-height: 50px"
                      :src="$initImage(scope.row.detail)"
                      :preview-src-list="srcList"
                    >
                      <template #error>
                        <div class="image-slot">
                          <span>暂无</span>
                        </div>
                      </template>
                    </el-image>
                  </template>
                  <template v-else-if="scope.row.type == 'vido'">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="点击播放视频"
                      placement="top"
                    >
                      <i
                        style="font-size: 30px; cursor: pointer"
                        class="el-icon-video-play"
                        @click="handleVideoVisible(scope.row.detail)"
                      ></i>
                      <!--<video
                        :src='$imgPath + scope.row.detail'
                        style="cursor: pointer"
                        width="100"
                        height="50"
                        loop="loop"
                        @click="handleVideoVisible(scope.row.detail)">
                      </video>-->
                    </el-tooltip>
                  </template>
                </span>
                <span v-else-if="item.prop === 'status'">
                  <el-switch
                    v-model="scope.row.status"
                    active-value="0"
                    inactive-value="1"
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </span>
                <span v-else-if="item.prop === 'type'">
                  {{
                    scope.row.type == "vido"
                      ? "视频"
                      : scope.row.type == "image"
                      ? "图片"
                      : "--"
                  }}
                </span>
                <span v-else-if="item.prop === 'content'">
                  <el-button
                    v-if="editorBtn"
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handlePreview(scope.row)"
                    >预览</el-button
                  >
                </span>
                <span
                  v-else-if="item.prop === 'createTime'"
                  style="
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                >
                  {{ scope.row.createTime || "--" }}
                </span>
                <span
                  v-else-if="item.prop === 'keywords'"
                  style="
                    overflow: hidden;
                    text-overflow: ellipsis;
                    line-clamp: 2;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                  "
                >
                  {{ scope.row.keywords || "--" }}
                </span>
                <span
                  v-else-if="item.prop === 'link'"
                  style="
                    overflow: hidden;
                    text-overflow: ellipsis;
                    line-clamp: 2;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    cursor: pointer;
                  "
                  @click="handleCopyLink(scope.row)"
                >
                  {{ scope.row.link || "--" }}
                </span>
                <span
                  v-else-if="item.prop === 'title'"
                  style="
                    overflow: hidden;
                    text-overflow: ellipsis;
                    line-clamp: 2;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                  "
                >
                  {{ scope.row.title || "--" }}
                </span>
                <span
                  v-else-if="item.prop === 'publishStatus'"
                  v-text="
                    scope.row.publishStatus === 0
                      ? '已发布'
                      : scope.row.publishStatus === 1
                      ? '未发布'
                      : '--'
                  "
                ></span>
                <template v-else>{{
                  scope.row[scope.column.property]
                }}</template>
              </template>
            </el-table-column>
          </template>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-info"
                @click="handleView(scope.row, 1)"
                >详情</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleView(scope.row, 2)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog
      append-to-body
      width="70%"
      :title="title"
      :visible.sync="open"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :disabled="disabled"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="right"
      >
        <template v-if="form.type == 'vido' || form.type == 'image'">
          <el-form-item
            v-if="showCasList"
            label="分类菜单"
            prop="cascaderValue"
          >
            <el-cascader
              style="width: 100%"
              clearable
              v-model="form.cascaderValue"
              :options="treeListArr"
              :props="cascaderProps"
              :show-all-levels="false"
              @change="handleCascader"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="视频名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入视频名称">
            </el-input>
          </el-form-item>
          <el-form-item label="启用状态" prop="status">
            <el-select
              style="width: 100%"
              v-model="form.status"
              placeholder="请选择状态(0-启用 1-停用)"
            >
              <el-option
                v-for="(i, idx) in statusList"
                :key="idx"
                :value="i.value"
                :label="i.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="视频封面"
            prop="coverImage"
            v-if="form.type == 'vido'"
          >
            <imageUpload v-model="form.coverImage" />
          </el-form-item>
          <el-form-item label="上传文件" prop="detail">
            <ele-upload-video
              v-if="form.type == 'vido'"
              v-model="form.detail"
              :file-size="100"
              :action="uploadVideo.uploadVideoUrl"
              :headers="uploadVideo.token"
              :file-type="uploadVideo.fileType"
              @error="handleUploadError"
              @input="getVideo"
            />
            <imageUpload v-if="form.type == 'image'" v-model="form.detail" />
          </el-form-item>
        </template>
        <template v-else>
          <el-row>
            <el-col :span="spanWidth">
              <el-form-item
                v-if="showCasList"
                label="分类菜单"
                prop="cascaderValue"
              >
                <el-cascader
                  style="width: 100%"
                  clearable
                  v-model="form.cascaderValue"
                  :options="treeListArr"
                  :props="cascaderProps"
                  :show-all-levels="false"
                  @change="handleCascader"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="spanWidth">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker
                  clearable
                  style="width: 100%"
                  v-model="form.createTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择修改创建时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="热门标识" prop="hotFlag">
                <el-select
                  style="width: 100%"
                  v-model="form.hotFlag"
                  placeholder="请选择热门标识(0-非热门 1-热门)"
                >
                  <el-option
                    v-for="(item, index) in hotFlagList"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最新标识" prop="newFlag">
                <el-select
                  style="width: 100%"
                  v-model="form.newFlag"
                  placeholder="请选择最新标识(0-非最新 1-最新)"
                >
                  <el-option
                    v-for="(i, idx) in newFlagList"
                    :label="i.label"
                    :value="i.value"
                    :key="idx"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="标题" prop="title">
                <el-input
                  v-model="form.title"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="路径" prop="path">
                <el-input
                  v-model="form.path"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="摘要" prop="summary">
                <el-input
                  v-model="form.summary"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关键词" prop="keywords">
                <el-input
                  v-model="form.keywords"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="来源" prop="origin">
                <el-input
                  v-model="form.origin"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外部链接" prop="link">
                <el-input
                  v-model="form.link"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="启用状态" prop="status">
                <el-select
                  style="width: 100%"
                  v-model="form.status"
                  placeholder="请选择状态(0-启用 1-停用)"
                >
                  <el-option
                    v-for="(i, idx) in statusList"
                    :key="idx"
                    :value="i.value"
                    :label="i.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发布状态" prop="publishStatus">
                <el-select
                  style="width: 100%"
                  v-model="form.publishStatus"
                  placeholder="请选择发布状态(0-发布 1-未发布)"
                >
                  <el-option
                    v-for="(i, idx) in publishStatusList"
                    :key="idx"
                    :value="i.value"
                    :label="i.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="封面图片" prop="coverImage">
            <imageUpload v-model="form.coverImage" />
          </el-form-item>
          <el-form-item label="内容">
            <editor
              v-if="update"
              v-model="form.content"
              :upload-url="uploadVideo.uploadVideoUrl"
              :read-only="readOnly"
              :min-height="400"
            />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="submitBtn" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 视频播放弹出框 -->
    <el-dialog
      title="视频详情"
      width="45%"
      append-to-body
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :visible.sync="videoVisible"
    >
      <div class="video">
        <video
          loop="loop"
          controls="controls"
          autoplay="autoplay"
          :src="videoSrc"
        ></video>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!--预览富文本内容-->
    <el-dialog title="预览" width="50%" :visible.sync="editorVisible">
      <div class="editor-show" v-html="editorContent"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editorVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import $ from "jquery";
import {
  listArticle,
  getArticle,
  delArticle,
  addArticle,
  updateArticle,
  changeArticleStatus,
} from "@/api/system/article";
import {
  listResource,
  getResource,
  addResource,
  updateResource,
  delResource,
  changeResourceStatus,
} from "@/api/system/resource";
import { listHead } from "@/api/system/head";
import { queryTreeList, listCategory } from "@/api/system/category";
import { contentHeadList, resourceHeadList } from "./head";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from "@/components/ImageUpload";
import Editor from "@/components/Editor";
import EleUploadVideo from "@/components/videoUpload";
import { getToken } from "@/utils/auth";

export default {
  name: "User",
  components: { Treeselect, ImageUpload, Editor, EleUploadVideo },
  data() {
    return {
      // 复选框数组
      selectionOptions: [],
      // 富文本预览显示隐藏
      editorBtn: true,
      // 富文本显示
      editorVisible: false,
      // 富文本预览内容
      editorContent: "",
      // 判断提交接口
      judgeSubmit: null,
      spanWidth: 12,
      // 显示级联选择器
      showCasList: true,
      // 区分查看详情的发布会和轮播图弹出框
      showDetail: false,
      // 上传视频时需要的参数
      uploadVideo: {
        uploadVideoUrl: this.$imgServicePath, // 上传的视频服务器地址
        // 上传时需要携带后台请求的token
        token: { Authorization: "Bearer " + getToken() },
        // acceptType: "MP4, WMV, RMVB, AVI, MPEG",
        fileType: ["mp4", "webm"],
      },
      submitBtn: false,
      videoSrc: "",
      videoVisible: false,
      // 表头
      tableHeadList: [],
      // 自定义表头
      // contentHeadList,
      // 富文本只读
      readOnly: false,
      // 组件刷新
      update: true,
      // 表单禁用
      disabled: false,
      // 表头数据
      articleHeadList: [],
      // 预览大图
      srcList: [],
      // 表格数据
      articleList: [],
      // 树形结构数据
      treeListArr: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 菜单名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 级联改造
      cascaderProps: {
        value: "id",
        label: "name",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        title: null,
        path: null,
        categoryId: "101",
        publishTime: null,
        publishStatus: null,
        sort: null,
        hotFlag: null,
        newFlag: null,
        summary: null,
        content: null,
        keywords: null,
        coverImage: null,
        origin: null,
        link: null,
        type: null,
        status: null,
        beginTime: null,
        endTime: null,
        model: null,
      },
      // 表单校验
      rules: {
        /*/cascaderValue: [
          {required: true, message: '请选择分类菜单', trigger: 'change'}
        ],*/
        createTime: [
          { required: true, message: "请选择修改创建时间", trigger: "change" },
        ],
        hotFlag: [
          { required: true, message: "请选择是否热门", trigger: "change" },
        ],
        newFlag: [
          { required: true, message: "请选择是否最新", trigger: "change" },
        ],
      },
      // 默认展开第一个
      defaultExpandTree: [],
      // 默认子节点
      defaultCurrentKey: 101,
      // 热门 非热门
      hotFlagList: [
        {
          label: "热门",
          value: 1,
        },
        {
          label: "非热门",
          value: 0,
        },
      ],
      // 标识
      newFlagList: [
        {
          label: "最新",
          value: 1,
        },
        {
          label: "非最新",
          value: 0,
        },
      ],
      // 启用状态
      statusList: [
        {
          label: "启用",
          value: 0,
        },
        {
          label: "停用",
          value: 1,
        },
      ],
      // 发布状态
      publishStatusList: [
        {
          label: "发布",
          value: 0,
        },
        {
          label: "未发布",
          value: 1,
        },
      ],
    };
  },
  watch: {
    // 根据名称筛选菜单树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {},
  created() {
    this.getList();
    this.getTreeMenuList();
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
    // this.getArticleHeadList()
  },
  methods: {
    // 预览富文本
    handlePreview(row) {
      this.editorVisible = true;
      this.editorContent = row.content;
    },
    // 上传视频出错
    handleUploadError(error) {
      console.log("error", error);
    },
    getVideo(response) {
      this.form.detail = this.$initImage(response.url);
    },
    handleVideoVisible(val) {
      this.videoSrc = this.$initImage(val);
      this.videoVisible = true;
    },
    /** 级联选择器选中 */
    handleCascader(val) {
      let params = val[val.length - 1];
      this.judgeSubmit = params;
      let formObj = this.form;
      if (params == 102) {
        formObj.model = val.toString();
        formObj.type = "vido";
        let { categoryId, ...newForm } = formObj;
        this.form = newForm;
      } else if (params == 107) {
        formObj.model = val.toString();
        formObj.type = "image";
        let { categoryId, ...newForm } = formObj;
        this.form = newForm;
      } else {
        formObj.categoryId = val.toString();
        formObj.type = null;
        let { model, ...newForm } = formObj;
        this.form = newForm;
      }
    },
    /** 改变日期 */
    changeDatePick(val) {
      if (Array.isArray(val)) {
        this.queryParams.beginTime = String(val[0]);
        this.queryParams.endTime = String(val[1]);
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
    },
    /** 内容【表头】列表 */
    /*getArticleHeadList() {
      listHead({bid: 'sys_article'}).then(response => {
        const listArr = []
        response.rows.forEach(params =>{
          listArr.push({
            id: params.id,
            label: params.dictName,
            prop: this.toHump(params.dictType)
          })
        })
        this.articleHeadList = listArr
      })
    },*/

    /** 查询树形结构列表 */
    getTreeMenuList() {
      listCategory().then((response) => {
        this.treeListArr = this.handleTree(response.rows, "id");
        this.defaultExpandTree.push(Number(this.treeListArr[0].id));
        // this.defaultCurrentKey = Number(this.treeListArr[0].children[0].id)
      });
    },
    /** 查询内容列表 */
    getList() {
      this.loading = true;
      this.tableHeadList = contentHeadList;
      listArticle(this.queryParams).then((response) => {
        const listArray = [];
        const listArr = [];
        response.rows.forEach((params) => {
          params.status = String(params.status);
          listArray.push(this.$imgPath + params.coverImage);
          listArr.push(params);
        });
        this.srcList = listArray;
        this.articleList = listArr;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getResourceList(id) {
      // let id = 102 || 107
      this.queryParams.model = id;
      let { categoryId, ...paramsData } = this.queryParams;
      listResource(paramsData).then((response) => {
        this.$nextTick(() => {
          this.tableHeadList = resourceHeadList;
        });
        const listArray = [];
        const listArr = [];
        response.rows.forEach((params) => {
          params.status = String(params.status);
          listArray.push(this.$imgPath + params.detail);
          listArr.push(params);
        });
        this.srcList = listArray;
        this.articleList = listArr;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.id == 102 || data.id == 107) {
        this.editorBtn = false;
        this.queryParams.model = data.id;
        let { categoryId, ...paramsData } = this.queryParams;
        listResource(paramsData).then((response) => {
          this.$nextTick(() => {
            this.tableHeadList = resourceHeadList;
          });
          const listArray = [];
          const listArr = [];
          response.rows.forEach((params) => {
            params.status = String(params.status);
            if (data.id == 102) {
              listArray.push(this.$initImage(params.coverImage));
            } else if (data.id == 107) {
              listArray.push(this.$initImage(params.detail));
            }
            listArr.push(params);
          });
          this.srcList = listArray;
          this.articleList = listArr;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        this.editorBtn = true;
        this.tableHeadList = contentHeadList;
        let { model, ...paramsData } = this.queryParams;
        paramsData.categoryId = data.id;
        this.queryParams = paramsData;
        this.getList();
      }
    },
    // 菜单状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      if (row.model) {
        this.$confirm('确认要"' + text + '""' + row.id + '"菜单吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return changeResourceStatus(row.id, row.status);
          })
          .then(() => {
            this.msgSuccess(text + "成功");
          })
          .catch(function () {
            row.status = row.status === "0" ? "1" : "0";
          });
      } else {
        this.$confirm(
          '确认要"' + text + '""' + row.categoryId + '"菜单吗?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return changeArticleStatus(row.id, row.status);
          })
          .then(() => {
            this.msgSuccess(text + "成功");
          })
          .catch(function () {
            row.status = row.status === "0" ? "1" : "0";
          });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.videoVisible = false;
      this.videoSrc = "";
      this.disabled = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        path: null,
        categoryId: null,
        publishTime: null,
        publishStatus: null,
        sort: null,
        hotFlag: null,
        newFlag: null,
        summary: null,
        content: null,
        keywords: null,
        coverImage: null,
        origin: null,
        link: null,
        type: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        status: null,
        beginTime: null,
        endTime: null,
        cascaderValue: null,
        name: null,
        detail: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selectionOptions = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【菜单内容】";
      this.showCasList = true;
      this.spanWidth = 12;
    },
    /** 查看详情、修改按钮 */
    handleView(row, type) {
      if (type == 1) {
        this.readOnly = true;
      } else {
        this.readOnly = false;
      }
      const id = row.id || this.ids;
      this.showCasList = false;
      this.spanWidth = 24;
      if (row.type == "vido" || row.type == "image") {
        getResource(id).then(({ data }) => {
          let valueArr = data.model.split(",");
          valueArr.forEach((item, index) => {
            valueArr[index] = parseInt(valueArr[index]);
          });
          data.cascaderValue = valueArr;
          this.form = data;
          this.open = true;
          if (type == 2) {
            this.title = "修改【菜单内容】";
            this.disabled = false;
          } else if (type == 1) {
            this.title = "查看详情";
            this.disabled = true;
          }
        });
      } else {
        this.reset();
        // 移除组件
        this.update = false;
        // 在组件移除后，重新渲染组件
        // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
        this.$nextTick(() => {
          this.update = true;
        });
        getArticle(id).then((response) => {
          let valueArr = response.data.categoryId.split(",");
          valueArr.forEach((item, index) => {
            valueArr[index] = parseInt(valueArr[index]);
          });
          response.data.cascaderValue = valueArr;
          this.form = response.data;
          this.open = true;
          if (type == 2) {
            this.title = "修改【菜单内容】";
            this.disabled = false;
          } else if (type == 1) {
            this.title = "查看详情";
            this.disabled = true;
          }
        });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.readOnly = false;
      this.reset();
      const id = row.id || this.ids;
      // 移除组件
      this.update = false;
      // 在组件移除后，重新渲染组件
      // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
      this.$nextTick(() => {
        this.update = true;
      });
      getArticle(id).then((response) => {
        let valueArr = response.data.categoryId.split(",");
        valueArr.forEach((item, index) => {
          valueArr[index] = parseInt(valueArr[index]);
        });
        response.data.cascaderValue = valueArr;
        this.form = response.data;
        this.open = true;
        this.title = "修改【菜单内容】";
        this.disabled = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.model) {
              let a = this.form.model.split(",");
              let b = a[a.length - 1];
              updateResource(this.form).then((response) => {
                if (b == 102) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getResourceList(102);
                } else if (b == 107) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getResourceList(107);
                }
              });
            } else {
              updateArticle(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
            /*updateArticle(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });*/
          } else if (this.judgeSubmit == 102) {
            addResource(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getResourceList(102);
            });
          } else if (this.judgeSubmit == 107) {
            addResource(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getResourceList(107);
            });
          } else {
            addArticle(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // async batchGetDetail() {
    //   try {
    //     for (let i = 0; i < this.articleList.length; i += 1) {
    //       const row = this.articleList[i];
    //       const id = row.id || this.ids;
    //       console.log(i, "row", row);
    //       if (row.type == "vido" || row.type == "image") {
    //         const { data } = await getResource(id);
    //         await this.batchSubmit(data);
    //         this.msgSuccess("修改成功");
    //       } else {
    //         const { data } = await getArticle(id);
    //         await this.batchSubmit(data);
    //         this.msgSuccess("修改成功");
    //       }
    //     }
    //   } catch (err) {
    //     console.log("查询出错", err);
    //   }
    // },
    // async batchSubmit(form) {
    //   if (form.content) {
    //     form.content = form.content.replace(
    //       /https:\/\/huaanelevator.oss-cn-shenzhen.aliyuncs.com/g,
    //       this.$imgPath
    //     );
    //   }
    //   if (form.id) {
    //     if (form.model) {
    //       return await updateResource(form);
    //     } else {
    //       return await updateArticle(form);
    //     }
    //   }
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;

      if (Array.isArray(ids)) {
        if (this.selectionOptions[0].model) {
          this.$confirm(
            '是否确认删除【菜单内容】编号为"' + ids + '"的数据项?',
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(function () {
              return delResource(ids);
            })
            .then(() => {
              if (this.selectionOptions[0].model == "1,102") {
                this.getResourceList(102);
              } else if (this.selectionOptions[0].model == "1,107") {
                this.getResourceList(107);
              }
              this.msgSuccess("删除成功");
            });
        } else {
          this.$confirm(
            '是否确认删除【菜单内容】编号为"' + ids + '"的数据项?',
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(function () {
              return delArticle(ids);
            })
            .then(() => {
              this.getList();
              this.msgSuccess("删除成功");
            });
        }
      } else {
        if (row.model) {
          this.$confirm(
            '是否确认删除【菜单内容】编号为"' + ids + '"的数据项?',
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(function () {
              return delResource(ids);
            })
            .then(() => {
              if (ids == 102) {
                this.getResourceList(102);
              } else if (107) {
                this.getResourceList(107);
              }
              this.msgSuccess("删除成功");
            });
        } else {
          this.$confirm(
            '是否确认删除【菜单内容】编号为"' + ids + '"的数据项?',
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(function () {
              return delArticle(ids);
            })
            .then(() => {
              this.getList();
              this.msgSuccess("删除成功");
            });
        }
      }
    },
    /** 自定义表头宽度 */
    handleColumnWidth(str) {
      let columnWidth = 0;
      for (let char of str) {
        if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
          // 如果是英文字符，为字符分配10个单位宽度，单位宽度可根据字体大小调整
          columnWidth += 10;
        } else if (char >= "\u4e00" && char <= "\u9fa5") {
          // 如果是中文字符，为字符分配14个单位宽度，单位宽度可根据字体大小调整
          columnWidth += 14;
        } else {
          // 其他种类字符，为字符分配10个单位宽度，单位宽度可根据字体大小调整
          columnWidth += 10;
        }
      }
      if (columnWidth < 120) {
        // 设置最小宽度
        columnWidth = 120;
      }
      return columnWidth + "px";
    },
    /** 复制功能 */
    handleCopyLink(row) {
      let _this = this;
      this.$copyText(row.link).then(
        function (e) {
          _this.$message({
            showClose: true,
            message: "复制成功",
            type: "success",
          });
        },
        function (e) {
          _this.$message({
            showClose: true,
            message: "复制失败，请手动复制",
            type: "error",
          });
        }
      );
    },
  },
  updated() {
    $(".editor-show").find("img").css("width", "100%");
  },
};
</script>
<style scoped lang="scss">
.video {
  position: relative;
  video {
    position: relative;
    width: 100%;
    height: 400px;
    left: 50%;
    transform: translateX(-50%);
  }
}

#caseContent {
  ::v-deep img {
    width: 50px;
    height: 50px;
  }
}
</style>
